<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<script>
  let arr = [
    {id: 1, name: '部门1', pid: 0},
    {id: 2, name: '部门2', pid: 1},
    {id: 3, name: '部门3', pid: 1},
    {id: 4, name: '部门4', pid: 3},
    {id: 5, name: '部门5', pid: 4},
  ]

  let result = [
    {
      id: 1,
      name: '部门1',
      pid: 0,
      children: [
        {
          id: 2, name: '部门2', pid: 1
        },
        {
          id: 3, name: '部门3', pid: 1,
          children: [
            {
              id: 4, name: '部门4', pid: 3,
              children: [{id: 5, name: '部门5', pid: 4}]
            }
          ]
        },
      ]
    },
  ]

  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i].id === arr[j].pid) {
        if (Array.isArray(arr[i].children)) {
          arr[i].children.push(arr[j])
        } else {
          arr[i].children = []
          arr[i].children.push(arr[j])
        }
      }
    }
  }

  console.log(arr);
</script>
</body>
</html>
